﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Configuration;
using System.Reflection;
using PRET.DBAdapter.DBAccess;
using PRET.ReportDataDefine.UIData;

namespace PRET.DBAdapter
{
    public class ServiceAdapter 
    {
        //private Configuration config;
        private SQLDataProcess sqlServer = null;
        private AttendanceDB attServer = null;
        //private readonly static string configPath = ".\\DBAdapter.dll.config";

        public ServiceAdapter()
        {
            //InitializeSQLConnect();
            //InitializeAttendanceDBConnect();
            if (sqlServer == null)
                InitializeSQLConnect();
            if (attServer == null)
                InitializeAttendanceDBConnect();
        }

        public void Dispose()
        {
            sqlServer.Dispose();
            attServer.Dispose();
        }

        private bool UsingAnalogData()
        {
            //string usingAnalog = this.config.ConnectionStrings.ConnectionStrings["UsingAnalogData"].ConnectionString;
            string usingAnalog = PRET.DBAdapter.Properties.Resources.UsingAnalogData;
            if (usingAnalog == "0")
                return false;
            else
                return true;
        }

        /// <summary>
        /// 初始化SQL数据库连接
        /// </summary>
        private void InitializeSQLConnect()
        {
            //ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            //map.ExeConfigFilename = configPath;
            //this.config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            string servername = PRET.DBAdapter.Properties.Resources.SQLServerName;
            string dbname = PRET.DBAdapter.Properties.Resources.SQLDBName;
            string userid = PRET.DBAdapter.Properties.Resources.SQLUserID;
            string pwd = PRET.DBAdapter.Properties.Resources.SQLPassWord;
            //string servername = this.config.ConnectionStrings.ConnectionStrings["SQLServerName"].ConnectionString;
            //string dbname = this.config.ConnectionStrings.ConnectionStrings["SQLCCDBName"].ConnectionString;
            //string userid = this.config.ConnectionStrings.ConnectionStrings["SQLUserID"].ConnectionString;
            //string pwd = this.config.ConnectionStrings.ConnectionStrings["SQLPassWord"].ConnectionString;
            sqlServer = new SQLDataProcess(servername, dbname, userid, pwd);
        }

        private void InitializeAttendanceDBConnect()
        {
            if (attServer != null)
            {
                attServer.Dispose();
            }
            //ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            //map.ExeConfigFilename = configPath;
            //this.config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            string servername = PRET.DBAdapter.Properties.Resources.AttDBServerName;
            string dbname = PRET.DBAdapter.Properties.Resources.AttDBName;
            string userid = PRET.DBAdapter.Properties.Resources.AttDBUserID;
            string pwd = PRET.DBAdapter.Properties.Resources.AttDBPassWord;
            //string servername = this.config.ConnectionStrings.ConnectionStrings["SQLServerName"].ConnectionString;
            //string dbname = this.config.ConnectionStrings.ConnectionStrings["SQLCCDBName"].ConnectionString;
            //string userid = this.config.ConnectionStrings.ConnectionStrings["SQLUserID"].ConnectionString;
            //string pwd = this.config.ConnectionStrings.ConnectionStrings["SQLPassWord"].ConnectionString;
            attServer = new AttendanceDB(servername, dbname, userid, pwd);
        }

        /// <summary>
        /// 得到挤出机相关的订单列表
        /// </summary>
        /// <returns></returns>
        public List<OrderCheckInfo> GetJCJOrderList()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            List<OrderCheckInfo> orderList = sqlServer.GetJCJOrderList();
            return orderList;
        }

        /// <summary>
        /// 得到均化机相关的订单列表
        /// </summary>
        /// <returns></returns>
        public List<OrderCheckInfo> GetJHJOrderList()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            List<OrderCheckInfo> orderList = sqlServer.GetJHJOrderList();
            return orderList;
        }

        public List<ProductionReport> GetProductionReport(OrderCheckInfo bn)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            List<ProductionReport> obj = sqlServer.GetProductionReport(bn);
            return obj;
        }

        public List<JHJReport> GetJHJReport(OrderCheckInfo bnInfo)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            List<JHJReport> obj = sqlServer.GetJHJReport(bnInfo);
            return obj;
        }

        public List<DeviceRunReport> GetDeviceRunReport()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            // TODO: 从后台获取所有的设备运行数据

            // 模拟数据
            return AnalogDataBuilder.BuildDeviceRunReportData();
        }

        public List<float> GetMeterUnitPrice()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetMeterUnitPrice();
        }

        public MeterReadingReport GetMeterReadingReport(DateTime startTime, DateTime endTime, float peakPrice, float genPrice, float lowPrice)
        {
            if (!this.UsingAnalogData())
            {
                if (sqlServer == null)
                    InitializeSQLConnect();
                MeterReadingReport obj = sqlServer.GetMeterReadingReport(startTime, endTime, peakPrice, genPrice, lowPrice);
                return obj;
            }
            else
            {
                // 模拟数据
                MeterReadingReport obj = AnalogDataBuilder.BuildMeterReadingReportData();
                obj.Summary.StartTime = startTime;
                obj.Summary.EndTime = endTime;
                return obj;
            }            
        }

        public List<string> GetHighLowDeviceList()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetHighLowDeviceList();
        }

        public List<HighLowStatusReport> GetHighLowStatusReport(string deviceID, DateTime month)
        {
            if (!this.UsingAnalogData())
            {
                if (sqlServer == null)
                    InitializeSQLConnect();
                List<HighLowStatusReport> retList = sqlServer.GetHighLowStatusReport(deviceID, month);
                return retList;
            }
            else
            {
                // 模拟数据
                return AnalogDataBuilder.BuildHighLowStatusReportData();
            }            
        }

        public HighLowVoltageReport GetHighLowVoltageReport(DateTime startTime, DateTime endTime)
        {
            return sqlServer.GetHighLowVoltageReport(startTime, endTime);
        }

        public List<ProductionReportSummaryForJSON> GetProLineStatus()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetProLineStatus();
        }

        public List<ProductiveTaskReport> GetProductiveTaskReport()
        {
            if (!this.UsingAnalogData())
            {
                if (sqlServer == null)
                    InitializeSQLConnect();
                // 从后台获取所有的生产任务数据
                List<ProductiveTaskReport> list = sqlServer.GetProductiveTaskReport();
                return list;
            }
            else
            {
                // 模拟数据
                return AnalogDataBuilder.BuildProductiveTaskReport();
            }
        }

        public List<ProductiveTaskReportTV> GetProductiveTaskReportForTV()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetProductiveTaskReportForTV();
        }

        public List<ProductionLineEfficiencyReport> GetProductionLineEfficiencyReport(DateTime year, Dictionary<string, int> quota)
        {
            if (!this.UsingAnalogData())
            {
                if (sqlServer == null)
                    InitializeSQLConnect();
                // 从后台获取生产线指定年份的效率数据数据
                List<ProductionLineEfficiencyReport> list = sqlServer.GetProductionLineEfficiencyReportForTV(year);
                //List<ProductionLineEfficiencyReport> list = sqlServer.GetProductionLineEfficiencyReport2(year, quota);
                list.Sort((left, right) =>
                {
                    int proline1 = int.Parse(left.ProductionLine.Substring(1));
                    int proline2 = int.Parse(right.ProductionLine.Substring(1));
                    return proline1 - proline2;
                });
                return list;
            }
            else
            {
                // 模拟数据
                return AnalogDataBuilder.BuildProductionLineEfficiencyReport();
            }
        }

        public Dictionary<string, int> GetEfficiencyQuota(int type)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetEfficiencyQuota(type);
        }


        public List<TeamEfficiencyReport> GetTeamEfficiencyReport2(DateTime year, Dictionary<string, int> quota = null)
        {
            if (!this.UsingAnalogData())
            {
                List<TeamEfficiencyReport> retList = new List<TeamEfficiencyReport>();
                if (sqlServer == null)
                    InitializeSQLConnect();
                Dictionary<string, List<double>> teamWeight = sqlServer.GetTeamYearWeight2(year);
                if (attServer == null)
                    InitializeAttendanceDBConnect();
                Dictionary<string, List<double>> teamWorkTime = attServer.GetTeamYearWorkTime(year);
                Dictionary<string, List<double>> teamRestTime = sqlServer.GetTeamRestTime(year);
                foreach (KeyValuePair<string, List<double>> item in teamWeight)
                {
                    // 要保证teamWeight和teamWorkTime在数量上保持一致
                    TeamEfficiencyReport team = new TeamEfficiencyReport();
                    team.TeamName = item.Key;
                    if (teamWorkTime[item.Key] != null && item.Value.Count == teamWorkTime[item.Key].Count)
                    {
                        double maxEffic = double.MinValue;
                        double minEffic = double.MaxValue;
                        // 遍历每一个月算出效率
                        for (int i = 0; i < item.Value.Count; i++)
                        {
                            double weight = item.Value[i];
                            team.Weight += weight;
                            double hours = 0, efficiency = 0;
                            hours = teamWorkTime[item.Key][i];
                            if (teamRestTime[item.Key] != null && teamRestTime[item.Key].Count > i)
                            {
                                hours -= teamRestTime[item.Key][i];
                                if (hours < 0)
                                    hours = 0;
                            }
                            if (hours != 0)
                            {
                                team.Hours += hours;
                                efficiency = Math.Round(weight / hours, 0);
                                maxEffic = maxEffic < efficiency ? efficiency : maxEffic;
                                if (efficiency > 0)
                                    minEffic = minEffic > efficiency ? efficiency : minEffic;
                            }
                            switch (i)
                            {
                                case 0:
                                    team.JanEfficiency = efficiency;
                                    team.JanHours = hours;
                                    team.JanWeight = weight;
                                    break;
                                case 1:
                                    team.FebEfficiency = efficiency;
                                    team.FebHours = hours;
                                    team.FebWeight = weight;
                                    break;
                                case 2:
                                    team.MarEfficiency = efficiency;
                                    team.MarHours = hours;
                                    team.MarWeight = weight;
                                    break;
                                case 3:
                                    team.AprEfficiency = efficiency;
                                    team.AprHours = hours;
                                    team.AprWeight = weight;
                                    break;
                                case 4:
                                    team.MayEfficiency = efficiency;
                                    team.MayHours = hours;
                                    team.MayWeight = weight;
                                    break;
                                case 5:
                                    team.JunEfficiency = efficiency;
                                    team.JunHours = hours;
                                    team.JunWeight = weight;
                                    break;
                                case 6:
                                    team.JulEfficiency = efficiency;
                                    team.JulHours = hours;
                                    team.JulWeight = weight;
                                    break;
                                case 7:
                                    team.AugEfficiency = efficiency;
                                    team.AugHours = hours;
                                    team.AugWeight = weight;
                                    break;
                                case 8:
                                    team.SepEfficiency = efficiency;
                                    team.SepHours = hours;
                                    team.SepWeight = weight;
                                    break;
                                case 9:
                                    team.OctEfficiency = efficiency;
                                    team.OctHours = hours;
                                    team.OctWeight = weight;
                                    break;
                                case 10:
                                    team.NovEfficiency = efficiency;
                                    team.NovHours = hours;
                                    team.NovWeight = weight;
                                    break;
                                case 11:
                                    team.DecEfficiency = efficiency;
                                    team.DecHours = hours;
                                    team.DecWeight = weight;
                                    break;
                            }
                        }
                        if (maxEffic != double.MinValue)
                            team.MaxEfficiency = Math.Round(maxEffic, 0);
                        if (minEffic != double.MaxValue)
                            team.MinEfficiency = Math.Round(minEffic, 0);
                        if (team.Hours > 0)
                            team.AvgEfficiency = Math.Round(team.Weight / team.Hours, 0);
                    }
                    if (quota != null)
                        team.EfficiencyQuota = quota[team.TeamName];
                    retList.Add(team);
                }

                // 2. 保存效率指标到DB中
                if (quota != null)
                    sqlServer.SaveEfficiencyQuota(year, quota, 2);
                return retList;

                //// 从后台获取班组指定年份的效率数据
                //List<TeamEfficiencyReport> list = sqlServer.GetTeamEfficiencyReport(year);
                //return list;
            }
            else
            {
                // 模拟数据
                return AnalogDataBuilder.BuildTeamEfficiencyReport();
            }
        }

        public List<TeamEfficiencyReport> GetTeamEfficiencyReport(DateTime year, Dictionary<string, int> quota = null)
        {
            if (!this.UsingAnalogData())
            {
                List<TeamEfficiencyReport> retList = new List<TeamEfficiencyReport>();
                if (sqlServer == null)
                    InitializeSQLConnect();
                Dictionary<string, List<double>> teamWeight = sqlServer.GetTeamYearWeight(year);
                if (attServer == null)
                    InitializeAttendanceDBConnect();
                Dictionary<string, List<double>> teamWorkTime = attServer.GetTeamYearWorkTime(year);
                Dictionary<string, List<double>> teamRestTime = sqlServer.GetTeamRestTime(year);
                foreach (KeyValuePair<string, List<double>> item in teamWeight)
                {
                    // 要保证teamWeight和teamWorkTime在数量上保持一致
                    TeamEfficiencyReport team = new TeamEfficiencyReport();
                    team.TeamName = item.Key;
                    if (teamWorkTime[item.Key] != null && item.Value.Count == teamWorkTime[item.Key].Count)
                    {
                        double maxEffic = double.MinValue;
                        double minEffic = double.MaxValue;
                        // 遍历每一个月算出效率
                        for (int i = 0; i < item.Value.Count; i++)
                        {
                            double weight = item.Value[i];
                            team.Weight += weight;
                            double hours = 0, efficiency = 0;
                            hours = teamWorkTime[item.Key][i];
                            if (teamRestTime[item.Key] != null && teamRestTime[item.Key].Count > i)
                            {
                                hours -= teamRestTime[item.Key][i];
                                if (hours < 0)
                                    hours = 0;
                            }
                            if (hours != 0)
                            {
                                team.Hours += hours;
                                efficiency = weight / hours;
                                maxEffic = maxEffic < efficiency ? efficiency : maxEffic;
                                if (efficiency > 0)
                                    minEffic = minEffic > efficiency ? efficiency : minEffic;
                            }
                            switch (i)
                            {
                                case 0:
                                    team.JanEfficiency = efficiency;
                                    team.JanHours = hours;
                                    team.JanWeight = weight;
                                    break;
                                case 1:
                                    team.FebEfficiency = efficiency;
                                    team.FebHours = hours;
                                    team.FebWeight = weight;
                                    break;
                                case 2:
                                    team.MarEfficiency = efficiency;
                                    team.MarHours = hours;
                                    team.MarWeight = weight;
                                    break;
                                case 3:
                                    team.AprEfficiency = efficiency;
                                    team.AprHours = hours;
                                    team.AprWeight = weight;
                                    break;
                                case 4:
                                    team.MayEfficiency = efficiency;
                                    team.MayHours = hours;
                                    team.MayWeight = weight;
                                    break;
                                case 5:
                                    team.JunEfficiency = efficiency;
                                    team.JunHours = hours;
                                    team.JunWeight = weight;
                                    break;
                                case 6:
                                    team.JulEfficiency = efficiency;
                                    team.JulHours = hours;
                                    team.JulWeight = weight;
                                    break;
                                case 7:
                                    team.AugEfficiency = efficiency;
                                    team.AugHours = hours;
                                    team.AugWeight = weight;
                                    break;
                                case 8:
                                    team.SepEfficiency = efficiency;
                                    team.SepHours = hours;
                                    team.SepWeight = weight;
                                    break;
                                case 9:
                                    team.OctEfficiency = efficiency;
                                    team.OctHours = hours;
                                    team.OctWeight = weight;
                                    break;
                                case 10:
                                    team.NovEfficiency = efficiency;
                                    team.NovHours = hours;
                                    team.NovWeight = weight;
                                    break;
                                case 11:
                                    team.DecEfficiency = efficiency;
                                    team.DecHours = hours;
                                    team.DecWeight = weight;
                                    break;
                            }
                        }
                        if (maxEffic != double.MinValue)
                            team.MaxEfficiency = Math.Round(maxEffic, 0);
                        if (minEffic != double.MaxValue)
                            team.MinEfficiency = Math.Round(minEffic, 0);
                        if (team.Hours > 0)
                            team.AvgEfficiency = team.Weight / team.Hours;
                    }
                    if (quota != null)
                        team.EfficiencyQuota = quota[team.TeamName];
                    retList.Add(team);
                }

                // 2. 保存效率指标到DB中
                if (quota != null)
                    sqlServer.SaveEfficiencyQuota(year, quota, 2);
                return retList;

                //// 从后台获取班组指定年份的效率数据
                //List<TeamEfficiencyReport> list = sqlServer.GetTeamEfficiencyReport(year);
                //return list;
            }
            else
            {
                // 模拟数据
                return AnalogDataBuilder.BuildTeamEfficiencyReport();
            }
        }

        public List<ProductionLineEfficiencyReport> GetProductionLineEfficiencyReportForTV(DateTime year)
        {
            if (!this.UsingAnalogData())
            {
                if (sqlServer == null)
                    InitializeSQLConnect();
                // 从后台获取生产线指定年份的效率数据数据
                List<ProductionLineEfficiencyReport> list = sqlServer.GetProductionLineEfficiencyReportForTV(year);
                return list;
            }
            else
            {
                // 模拟数据
                return AnalogDataBuilder.BuildProductionLineEfficiencyReport();
            }
        }

        public TVControlInfo ShowMessage()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.ShowMessage();
        }

        public ShowConfig GetShowConfig()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetShowConfig();
        }

        public void CorrectJCJOrderTime(OrderCheckInfo order)
        {
            sqlServer.CorrectJCJOrderTime(order);
        }
        public void CorrectJHJOrderTime(OrderCheckInfo order)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            sqlServer.CorrectJHJOrderTime(order);
        }

        public void IgnoreERPOrderTime(OrderCheckInfo order)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            sqlServer.IgnoreERPOrderTime(order);
        }

        public List<Dictionary<string, List<EmployeAttendance>>> GetAllDepEmployeAttendance(DateTime month)
        {
            if (attServer == null)
                InitializeAttendanceDBConnect();
            return attServer.GetAllDepEmployeAttendance(month);
        }

        public TeamAttendanceMain GetAllTeamAttendance(DateTime month)
        {
            TeamAttendanceMain team = new TeamAttendanceMain();
            if (sqlServer == null)
                InitializeSQLConnect();
            team.TeamHour = sqlServer.GetTeamAttendanceHours(month);
            if (attServer == null)
                InitializeAttendanceDBConnect();
            team.TeamList = attServer.GetAllTeamAttendance(month);
            TeamAttendanceRestHours teamHour = new TeamAttendanceRestHours();
            foreach(TeamAttendance item in team.TeamList)
            {
                teamHour.ATeamHours += item.ATeamHours;
                teamHour.BTeamHours += item.BTeamHours;
                teamHour.CTeamHours += item.CTeamHours;
                teamHour.DTeamHours += item.DTeamHours;
                teamHour.ETeamHours += item.ETeamHours;
                teamHour.FTeamHours += item.FTeamHours;
                teamHour.JXTeamHours += item.JXTeamHours;
                teamHour.ColorTeamHours += item.ColorTeamHours;
                teamHour.FZTeamHours += item.FZTeamHours;
            }
            team.TeamHour = teamHour - team.TeamHour;
            return team;
        }

        public void SetTeamAttendanceHours(double AHours, double BHours, double CHours, double DHours, double EHours, double FHours, DateTime month)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            sqlServer.SetTeamAttendanceHours(AHours, BHours, CHours, DHours, EHours, FHours, month);
        }

        public List<TeamAttendanceRestHours> GetTeamAttendanceHoursList(DateTime month)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetTeamAttendanceHoursList(month);
        }

        public List<HSMLJData> GetHSMLJReport(DateTime date)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            DateTime startTime = date.Date;
            DateTime endTime = date.Date.AddDays(1).AddSeconds(-1);
            return sqlServer.GetHSMLJReport(startTime, endTime);
        }

        /// <summary>
        /// 得到所有生产线这一年的待机状态
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        public List<ProductionLineStandby> GetProductionLineStandby(DateTime year)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetProductionLineStandby2(year);
        }

        public TVControlInfo GetTVControlInfo()
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            return sqlServer.GetTVControlInfo();
        }

        public void SaveTVControlInfo(TVControlInfo info)
        {
            if (sqlServer == null)
                InitializeSQLConnect();
            sqlServer.SaveTVControlInfo(info);
        }
    }
}
